package com.mask.boot.controller;


import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mask.boot.entity.User;
import com.mask.boot.mapper.UserMapper;
import com.mask.boot.service.UserService;
import com.mask.boot.util.R;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.concurrent.TimeUnit;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author hx
 * @since 2021-11-19
 */
@RestController
@RequestMapping("/user")
@Api(tags = "用户管理")
@Slf4j
public class UserController {

    @Autowired
    private User user;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private UserService userService;

    @GetMapping("/{number}/{size}")
    @ApiOperation("分页查询")
    public R getPageList(
            @ApiParam("页码") @PathVariable("number") Integer number,
            @ApiParam("页数") @PathVariable("size") Integer size){
        Page<User> page = new Page<>(number, size);
        Page<User> list = user.selectPage( page, null);
        return R.result("200","success","分页查询成功",list);
    }

    @PostMapping("/insert")
    @ApiOperation("添加用户")
    public R insert(User request){
        BeanUtils.copyProperties(request,user);
        boolean insert = user.insert();
        if (insert){
            return R.result("200","success","添加用户成功");
        }else {
            return R.result("500","error","添加用户失败");
        }

    }

    /**
     * 乐观锁
     * @return
     */
    @SneakyThrows
    @PostMapping("/version")
    @ApiOperation("乐观锁")
    public R version(){
        Object lock = new Object();

        //多线程模拟乐观锁，多个线程同时修改同一条数据会出现什么问题

//        new Thread(() -> {
//            User user = new User();
//            User result = user.selectById("b89736dfaae722f735ab722974b3a352");
//            log.info("线程A查询结果:{}",result);
//        },"A").start();


//        User user1 = new User();
//        user1.setId("b89736dfaae722f735ab722974b3a352").setNick("张三B");
//        boolean b = user1.updateById();
//        log.info("线程B修改结果:{}",b);
//
////        new Thread(() -> {
////
////        },"B").start();
//
//        User user2 = new User();
//        user2.setId("b89736dfaae722f735ab722974b3a352").setNick("张三C");
//        boolean c = user2.updateById();
//        log.info("线程C修改结果:{}",c);

//
//        //睡眠一秒，便于观察
        TimeUnit.SECONDS.sleep(1);
        User user1 = user.selectById("b89736dfaae722f735ab722974b3a352");
        log.info("查询结果1:{}",user1);
        user1.setNick("张三9");
        boolean b = user1.updateById();
//
        log.info("查询结果中...");
        User userR = this.user.selectById("b89736dfaae722f735ab722974b3a352");
        return R.result("200","success","更新成功",userR.getNick());
    }

}

